package com.kaibes.im.utils;

import java.io.File;
import java.util.HashMap;
import java.util.Set;

import com.kaibes.im.model.KaibesFile;

public class KaibesFilesUtil {

    private int maxFile;
    private HashMap<String, KaibesFile> kaibesFiles;

    public KaibesFilesUtil(int maxFile) {
	this.maxFile = maxFile;
	this.kaibesFiles = new HashMap<String, KaibesFile>();
    }

    public KaibesFilesUtil() {
	this.maxFile = 65535;
	this.kaibesFiles = new HashMap<String, KaibesFile>();
    }

    public KaibesFile addKabesFile(KaibesFile kaibesFile) {
	if (kaibesFiles.size() < maxFile) {
	    kaibesFiles.put(kaibesFile.getName(), kaibesFile);
	    return kaibesFile;
	} else {
	    return null;
	}
    }

    public boolean hasKaibesFile(String filename) {
	return kaibesFiles.containsKey(filename);
    }

    public void clean() {
	Set<String> keys = kaibesFiles.keySet();
	String[] keysStr = new String[keys.size()];
	keys.toArray(keysStr);
	for (int i = 0; i < keysStr.length; i++) {
	    removeKaibesFile(keysStr[i]);
	}
    }

    public void removeKaibesFile(String filename) {
	kaibesFiles.get(filename).close();
	kaibesFiles.remove(filename);
    }

    public void removeKaibesFileNotClose(String filename) {
	kaibesFiles.remove(filename);
    }

    public KaibesFile getKaibesFileAndRemoved(String filename) {
	KaibesFile kaibesFile = kaibesFiles.get(filename);
	removeKaibesFile(filename);
	return kaibesFile;
    }

    public KaibesFile getKaibesFile(String filename) {
	return kaibesFiles.get(filename);
    }

    public void setMaxFile(int maxFile) {
	this.maxFile = maxFile;
    }

    public void cacheRenameToFile(File parent, KaibesFile cacheFile) {
	cacheFile.close();
	File file = new File(parent, cacheFile.getParentFile().getName()
		+ File.separator + cacheFile.getName());
	if (!file.getParentFile().exists()) {
	    file.getParentFile().mkdir();
	}
	cacheFile.renameTo(file);
    }

    public int size() {
	return kaibesFiles.size();
    }

}
